package javango.forms.fields;

import java.util.Map;

import javango.forms.widgets.DecimalInputWidget;
import javango.forms.widgets.Widget;
import javango.forms.widgets.WidgetFactory;

import org.apache.commons.lang.StringUtils;

import com.google.inject.Inject;

/**
 * Implements a field that cleans itself as an Double value.
 * 
 * @author johns
 *
 */
public class DoubleField extends AbstractField<Double> {

	public final static String ERROR_NUMBER_NOT_VALID = "Double number not valid";
	public final static String ERROR_MAX_DECIMAL_PLACES = "Ensure that there are no more than %s decimal places.";
	
	protected Integer decimalPlaces;
	
	@Inject
	public DoubleField(WidgetFactory widgetFactory) {
		super(widgetFactory);
		setWidget(DecimalInputWidget.class);
	}

	public Double clean(String value, Map<String, String> errors) {
		if (StringUtils.isEmpty(value)) {
			if (this.isRequired()) {
				errors.put(getName(), REQUIRED_ERROR);
				return null;
			} else if (isAllowNull()) {
				return null;
			} else {
				return 0.0;
			}
			}
		try {
			if (getDecimalPlaces() != null) {
				int pos = value.indexOf('.');
				if (pos != -1) {
					if (value.length() - pos > decimalPlaces + 1) {
						errors.put(this.getName(), String.format(ERROR_MAX_DECIMAL_PLACES, decimalPlaces));
					}
				}
			}
			return Double.valueOf(value);
		} catch (NumberFormatException e) {
			errors.put(this.getName(), ERROR_NUMBER_NOT_VALID);
		}
		return null;
	}

	@Override
	public Widget getWidget() {
		Widget w = super.getWidget();
		if (getDecimalPlaces() != null && w instanceof DecimalInputWidget) {
			((DecimalInputWidget)w).setDecimalPlaces(getDecimalPlaces());
		}
		return w;
	}

	public Integer getDecimalPlaces() {
		return decimalPlaces;
	}

	public void setDecimalPlaces(Integer decimalPlaces) {
		this.decimalPlaces = decimalPlaces;
	}

}
